package com.sgb.jicai.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.sgb.jicai.R;
import com.sgb.jicai.databinding.ActivityJcProductmodelBinding;
import com.sgb.jicai.entity.AttrsBeans;
import com.sgb.jicai.entity.DetailsBean;
import com.sgb.jicai.entity.PriceRulesBean;
import com.sgb.jicai.entity.SupplierPublishBean;
import com.sgb.jicai.view.adapter.ProductModelAdaptrer;
import com.sgb.jicai.view.adapter.SpecsPriceAdaptrer;
import com.sgb.jicai.viewmodel.JiCaiProductModel;
import com.sgb.link.entity.GetSkuEntity;
import com.sgb.link.entity.GoodsSkuChild;
import com.sgb.link.utils.NumericalTransformationTool;
import com.swgk.core.base.AppActivity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Time:2021/7/23
 * AUTHOR:F_Q
 * Description:规格型号选项界面
 */
public class JiCaiProductModelAct extends AppActivity {

    private ActivityJcProductmodelBinding binding;
    JiCaiProductModel viewModel;
    private SupplierPublishBean bean;
    //规格型号adapter
    private ProductModelAdaptrer adapter;
    private SpecsPriceAdaptrer specspriceadaptrer;
    private String type = "";
    private boolean isProductModel;//是否是回显数据
    private boolean isNewData = false;//历史记录和新的规格型号接口是否存在一样的属性，存在展示选中状态，不存在没有选中状态
    List<DetailsBean> historydetails ;//用来记录用户上次保存的规格型号信息
    private boolean isRefactoring = false;//设置数据是是否有相同规格型号的产品，存在替换，不存在就处理数据
    private String originalPrice = "";//记录之前的价格信息

    @Override
    protected void initView() {
        super.initView();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_jc_productmodel);
        viewModel = new ViewModelProvider(this).get(JiCaiProductModel.class);
        viewModel.setActivity(JiCaiProductModelAct.this);
        binding.topLayout.titleView.setText("规格型号");
        binding.absent.contactPrice.setInfilterType(ItemInputTextView.TYPE_NUM);
        binding.topLayout.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        binding.save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });
        bean = (SupplierPublishBean) getIntent().getSerializableExtra("bean");
        viewModel.getSku(bean.getThirdType());
        //规格型号adapter
        adapter = new ProductModelAdaptrer(this, null);
        binding.exist.recyclerview1.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.exist.recyclerview1.setAdapter(adapter);
        adapter.setOperationData(new ProductModelAdaptrer.OperationData() {
            @Override
            public void OperationData(Map<Integer, HashSet<GoodsSkuChild>> setMap) {
                boolean isAllSelected = true;
                int count = setMap.values().size();
                for (int i = 0; i < count; i++) {
                    HashSet<GoodsSkuChild> goodsSkuChildren = setMap.get(i);
                    if (goodsSkuChildren == null || goodsSkuChildren.size() == 0) {
                        isAllSelected = false;
                        break;
                    }
                }
                if (isAllSelected) {
                    ArrayList<List<GoodsSkuChild>> lists = new ArrayList<>();
                    for (int i = 0; i < adapter.getDatas().size(); i++) {
                        List<GoodsSkuChild> twoList = new ArrayList<>();
                        List<GoodsSkuChild> list = adapter.getDatas().get(i).getList();
                        for (int j = 0; j < list.size(); j++) {
                            if (list.get(j).isOnClick()) {
                                twoList.add(list.get(j));
                            }
                        }
                        lists.add(twoList);
                    }
                    List<List<GoodsSkuChild>> descartes = getDescartes(lists);
                    // Log.e("tag得到的数据集合", descartes.toString());
                    OperationDataList(descartes);
                } else {
                    SpecsPriceAdaptrerData(new ArrayList<>(), false);
                }
            }
        });
    }


    @Override
    protected void init() {
        super.init();
        isProductModel = getIntent().getBooleanExtra("isProductModel", false);
    }

    //没有规则型号时保存的数据信息
    private void NoProductModelData(Intent intent) {
        List<PriceRulesBean> data = binding.absent.noSkuPurchaseQuantity.getData();
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                PriceRulesBean datum = data.get(i);
                if (TextUtils.isEmpty(datum.getIntervalStartValue())) {
                    MToast.showToast(getApplicationContext(), "请输入第" + datum.getSort() + "条起始采购量");
                    return;
                }
                if (TextUtils.isEmpty(datum.getIntervalEndValue())) {
                    MToast.showToast(getApplicationContext(), "请输入第" + datum.getSort() + "条结束采购量");
                    return;
                }
                if (TextUtils.isEmpty(datum.getPrice())) {
                    MToast.showToast(getApplicationContext(), "请输入第" + datum.getSort() + "条价格");
                    return;
                }
                if (Double.parseDouble(datum.getPrice()) <= 0) {
                    MToast.showToast(getApplicationContext(), "第" + datum.getSort() + "条价格不能小于等于0");
                    return;
                }
                if (Double.parseDouble(datum.getIntervalStartValue()) >= Double.parseDouble(datum.getIntervalEndValue())) {
                    MToast.showToast(getApplicationContext(), "第" + datum.getSort() + "条结束采购量必须大于起始采购量");
                    return;
                }
            }
            intent.putExtra("data", (Serializable) data);
            intent.putExtra("price", binding.absent.contactPrice.getContent());
            setResult(Activity.RESULT_OK, intent);
            finish();

        } else {
            MToast.showToast(getApplicationContext(), "请添加采购量/价格列表信息！");
            return;
        }

    }

    /**
     * 数据组装处理
     */
    private static List<List<GoodsSkuChild>> getDescartes(ArrayList<List<GoodsSkuChild>> lists) {
        List<List<GoodsSkuChild>> returnList = new ArrayList<>();
        descartesRecursive(lists, 0, returnList, new ArrayList());
        return returnList;
    }

    /**
     * 数据组装处理
     */
    private static void descartesRecursive(ArrayList<List<GoodsSkuChild>> originalList, int position, List<List<GoodsSkuChild>> returnList, List<GoodsSkuChild> cacheList) {
        List<GoodsSkuChild> originalItemList = originalList.get(position);
        for (int i = 0; i < originalItemList.size(); i++) {
            //最后一个复用cacheList，节省内存
            List childCacheList = (i == originalItemList.size() - 1) ? cacheList : new ArrayList<>(cacheList);
            childCacheList.add(originalItemList.get(i));
            if (position == originalList.size() - 1) {//遍历到最后退出递归
                returnList.add(childCacheList);
                continue;
            }
            descartesRecursive(originalList, position + 1, returnList, childCacheList);
        }
    }

    /**
     * 根据规格和材质处理规格组合及价格数据列表信息
     */
    private void OperationDataList(List<List<GoodsSkuChild>> descartes) {
        DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        //规格列表
        List<DetailsBean> DetailsBean = new ArrayList<>();
        for (int i = 0; i < descartes.size(); i++) {
            List<GoodsSkuChild> goodsSkuChildren = descartes.get(i);
            String shopNames = "";
            List<AttrsBeans> attrs = new ArrayList<>();
            for (int k = 0; k < goodsSkuChildren.size(); k++) {
                String paramData = "";
                String IsPrice = "";
                GoodsSkuChild goodsSkuChild = goodsSkuChildren.get(k);
                if (!TextUtils.isEmpty(shopNames)) {
                    shopNames = shopNames + "-" + goodsSkuChild.getVal();
                } else {
                    shopNames = goodsSkuChild.getVal();
                }
                for (GetSkuEntity data : adapter.getDatas()) {
                    if (data.getId().equals(goodsSkuChild.getAttribute())) {
                        paramData = data.getParamData();
                    }
                    IsPrice = data.getIsPrice();
                }
                //规格字段组装数据
                //String attribute, String value, String no, String name, String sku, String parentId
                attrs.add(new AttrsBeans(goodsSkuChild.getAttribute(), goodsSkuChild.getVal(), goodsSkuChild.getValId(), paramData, IsPrice, goodsSkuChild.getAttribute()));
            }
            //规格型号数据列表组装
            //String brandsName, String brandsNo, String lowBuy, String unit, List<AttrsBeans> attrs, String name
            DetailsBean detailsBean = new DetailsBean(bean.getBrandsName(), bean.getBrandsNo(), bean.getLowBuy(), bean.getUnit(), attrs, shopNames, bean.getUnitName());
            //每个商品条目默认带一个价格区间列表
            List<PriceRulesBean> PriceRulesBeanList = new ArrayList<>();
            PriceRulesBeanList.add(new PriceRulesBean(i + 1 + ""));
            detailsBean.setPriceRules(PriceRulesBeanList);
            DetailsBean.add(detailsBean);
        }
        if (DetailsBean.size() > 0) {
            // Log.e("tag最终组装数据集合", DetailsBean.toString());
         /*   if (isProductModel) {
                for (DetailsBean detailsBean : DetailsBean) {
                    for (DetailsBean detail : bean.getDetails()) {
                        if (!TextUtils.isEmpty(detail.getName())) {
                            if (detailsBean.getName().equals(detail.getName())) {
                                isRefactoring = true;
                                Collections.replaceAll(DetailsBean, detailsBean, detail);
                            }
                        }
                    }
                }
            }*/
            SpecsPriceAdaptrerData(DetailsBean, false);
        }
        DialogHelper.dismissProgressDialog();
    }

    //规格组合及价格adapter
    private void SpecsPriceAdaptrerData(List<DetailsBean> DetailsBean, boolean historicalData) {
        specspriceadaptrer = new SpecsPriceAdaptrer(getApplicationContext(), DetailsBean, historicalData);
        binding.exist.recyclerview2.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.exist.recyclerview2.setAdapter(specspriceadaptrer);
        binding.exist.recyclerview2.smoothScrollToPosition(0);
        binding.nestedScrollview.scrollTo(0, 0);
        specspriceadaptrer.setOperationDelete(new SpecsPriceAdaptrer.OperationDelete() {
            @Override
            public void Delete(int pos) {
                //删除数据清楚数据信息
                specspriceadaptrer.getDatas().remove(pos);
                specspriceadaptrer.notifyDataSetChanged();
            }
        });
    }


    /**
     * 有规格展示
     *
     * @param data
     */
    public void isSku(List<GetSkuEntity> data) {
        if (data != null && data.size() > 0) {
            type = "1";
            binding.exist.getRoot().setVisibility(View.VISIBLE);
            binding.absent.getRoot().setVisibility(View.GONE);
            adapter.setDatas(data);
            if (isProductModel) { //是否回显数据
                try {
                    historydetails = NumericalTransformationTool.deepCopy(bean.getDetails());  //调用该方法  //保存历史数据
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                List<GetSkuEntity> dataList = adapter.getDatas();//获取当前展示的规格型号信息
                //更新规格型号选中状态
                updateAdapter(bean.getDetails(), dataList);
                if (isNewData) {
                    SpecsPriceAdaptrerData(bean.getDetails(), true);
                }
            }
        } else {
            type = "2";
            binding.exist.getRoot().setVisibility(View.GONE);
            binding.absent.getRoot().setVisibility(View.VISIBLE);
            //是否存在规格型号
            if (isProductModel) {
                try {
                    historydetails = NumericalTransformationTool.deepCopy(bean.getDetails());  //调用该方法  //保存历史数据
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                List<DetailsBean> details = bean.getDetails();
                originalPrice = details.get(0).getOriginalPrice();
                binding.absent.contactPrice.setContent(originalPrice + "");
                binding.absent.noSkuPurchaseQuantity.setData(details.get(0).getPriceRules());
                binding.absent.noSkuPurchaseQuantity.setUnit(bean.getUnitName());
            }
        }

    }

    //更新规格型号数据
    private void updateAdapter(List<DetailsBean> details, List<GetSkuEntity> dataList) {
        for (int i = 0; i < details.size(); i++) {
            List<AttrsBeans> attrs = details.get(i).getAttrs();//获取规格型号数据列表   参考实体类字段
            for (AttrsBeans attr : attrs) {
                for (int j = 0; j < dataList.size(); j++) {
                    GetSkuEntity GetSkuEntitySata = dataList.get(j);
                    if (attr.getName().equals(GetSkuEntitySata.getParamData())) {//根据规格型号列表和数据当前集采规则字段名称做对比查看是否符合
                        List<GoodsSkuChild> list = GetSkuEntitySata.getList();
                        for (GoodsSkuChild goodsSkuChild : list) {//修改符合数据的数据状态
                            if (attr.getValue().equals(goodsSkuChild.getVal())) {
                                goodsSkuChild.setOnClick(true);
                                adapter.saveSelected(goodsSkuChild, j);
                                isNewData = true;
                            }
                        }
                    }
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    //保存数据
    private void saveData() {
        Intent intent = new Intent();
        intent.putExtra("type", type);
        if (type.equals("1")) {
            if (specspriceadaptrer != null && specspriceadaptrer.getDatas() != null && specspriceadaptrer.getDatas().size() > 0) {
                for (DetailsBean data : specspriceadaptrer.getDatas()) {
                    List<PriceRulesBean> priceRules = data.getPriceRules();
                    if (priceRules != null && priceRules.size() > 0) {
                        for (int i = 0; i < priceRules.size(); i++) {
                            PriceRulesBean priceRule = priceRules.get(i);
                            if (TextUtils.isEmpty(priceRule.getIntervalStartValue())) {
                                MToast.showToast(getApplicationContext(), "请输入第" + priceRule.getSort() + "条起始采购量");
                                return;
                            }
                            if (TextUtils.isEmpty(priceRule.getIntervalEndValue())) {
                                MToast.showToast(getApplicationContext(), "请输入第" + priceRule.getSort() + "条结束采购量");
                                return;
                            }
                            if (TextUtils.isEmpty(priceRule.getPrice())) {
                                MToast.showToast(getApplicationContext(), "请输入第" + priceRule.getSort() + "条价格");
                                return;
                            }
                            if (Double.parseDouble(priceRule.getPrice()) <= 0) {
                                MToast.showToast(getApplicationContext(), "第" + priceRule.getSort() + "条价格不能小于等于0");
                                return;
                            }
                            if (Double.parseDouble(priceRule.getIntervalStartValue()) >= Double.parseDouble(priceRule.getIntervalEndValue())) {
                                MToast.showToast(getApplicationContext(), "第" + priceRule.getSort() + "条结束采购量必须大于起始采购量");
                                return;
                            }
                        }
                    } else {
                        MToast.showToast(getApplicationContext(), "请添加采购量/价格列表信息！");
                        return;
                    }
                }
                intent.putExtra("adapter", (Serializable) specspriceadaptrer.getDatas());
                setResult(Activity.RESULT_OK, intent);
                finish();
            } else {
                MToast.showToast(getApplicationContext(), "请添加采购量/价格列表信息！");
                return;
            }
        } else {
            NoProductModelData(intent);
        }
    }

    @Override
    public void onBackPressed() {
        initDialog();
    }

    public void initDialog() {
        new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                .setTitle("温馨提示")
                .setMsg("所填写的内容是否保存？")
                .setDialogCallBack(new CommonDialog.DialogCallBack() {
                    @Override
                    public void onRightClick() {
                        saveData();//保存当前列表数据
                    }

                    @Override
                    public void onLeftClick() {
                        finish();
                       /* //是否为回显数据
                        if (isProductModel) {
                            Intent intent = new Intent();
                            intent.putExtra("type", type);
                            if (type.equals("1")) {
                                intent.putExtra("adapter", (Serializable) historydetails);
                            } else {
                                intent.putExtra("data", (Serializable) historydetails);
                                intent.putExtra("price", originalPrice+"");
                            }
                            setResult(RESULT_OK, intent);
                            finish();
                        } else {
                            finish();
                        }*/
                    }
                }).show();
    }

    ;
}
